package com.example.demo.service.serviceImpl;
import com.example.demo.dao.monDao.PersonResultDao;
import com.example.demo.dao.monDao.PersonResultGetDao;
import com.example.demo.dto.monDTO.DBObjectList;
import com.example.demo.dto.monDTO.PersonResultMongo;
import com.example.demo.service.PersonResultService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class PersonResultServiceImpl implements PersonResultService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private PersonResultDao personResultDao;

    public DBObjectList getRecordList(String openid, Integer limit, Integer skip) {
        DBCollection dbCollection = mongoTemplate.getCollection("personResultMongo");
        DBObject dbObject = new BasicDBObject("openid",openid);
        DBObject sortTime = new BasicDBObject("createTime",-1);
        DBCursor dbCursor =  dbCollection.find(dbObject).sort(sortTime).limit(limit).skip(skip);
        int size =  dbCollection.find(dbObject).size();
//        System.out.println(dbCursor.toArray());
        DBObjectList dbObjectList = new DBObjectList();
        dbObjectList.setList(dbCursor.toArray());
        dbObjectList.setTotalSize(size);
        return dbObjectList;
    }
    public List<PersonResultMongo> getResultMongo(String openid, Pageable pageable){
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");   //降序----根据创建时间来进行降序
        log.info("page={},size={}",pageable.getPageNumber(),pageable.getPageSize());
        PageRequest request = new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),sort);  //第0页，取一条
        Page<PersonResultMongo> eventPage = personResultDao.findByOpenid(openid,request);
        return eventPage.getContent();
    }
}
